package com.hengxinguotong.zhihuichengjian.ui.quality;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.QualityListAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.SecurityListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Quality;
import com.hengxinguotong.zhihuichengjian.bean.QualityListRes;
import com.hengxinguotong.zhihuichengjian.bean.Security;
import com.hengxinguotong.zhihuichengjian.bean.SecurityListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.DailySecurityTestActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityQuestionActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityTestActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 质量检查列表
 * Created by liux on 2017/3/7.
 */

public class QualityListActivity extends BaseActivity {
    private static final String TAG = "QualityListActivity";
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.add)
    HXTextView add;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;

    private QualityListAdapter qualityListAdapter;
    private SecurityListAdapter securityListAdapter;
    private int type = Constants.QUALITY;//1 质量  2安全 3日常安全
    private int pageIndex = 1;
    private List<Quality> qualities;
    private List<Security> securities;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.UPDATE:
                    if(type == Constants.QUALITY ||
                            type == Constants.QUALITY_QUESTION||
                            type == Constants.QUALITY_SUPERVISE){
                        List<Quality> datas = (List<Quality>) msg.obj;
                        addQualityData(datas);
                    }else {
                        List<Security> datas = (List<Security>) msg.obj;
                        addSecurityData(datas);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", Constants.QUALITY);
        initView();
        initData();
    }

    private void initView() {
        add.setVisibility(hasAdd()?View.VISIBLE:View.GONE);
        if (type == Constants.QUALITY) {
            titleTv.setText("质量检查列表");
        } else if (type == Constants.SECURITY) {
            titleTv.setText("分项检查列表");
        } else if (type == Constants.DAILY_SECURITY){
            titleTv.setText("日常检查列表");
        } else if (type == Constants.QUALITY_QUESTION){
            titleTv.setText("质量问题列表");
        } else if (type == Constants.SECURITY_QUESTION){
            titleTv.setText("安全问题列表");
        }  else if (type == Constants.QUALITY_SUPERVISE){
            titleTv.setText("质量监督列表");
        }  else if (type == Constants.SECURITY_SUPERVISE){
            titleTv.setText("安全监督列表");
        }  else if (type == Constants.CIVILIZED_CONSTRUCTION_SUPERVISE) {
            titleTv.setText("文明施工监督列表");
        }

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if(type == Constants.QUALITY || type == Constants.QUALITY_QUESTION || type == Constants.QUALITY_SUPERVISE){
            qualities = new ArrayList<>();
            qualityListAdapter = new QualityListAdapter(this, qualities);
            qualityListAdapter.setType(type);
            qualityListAdapter.setClickListener(qClicklistener);
            dataRv.setAdapter(qualityListAdapter);
        }else {
            securities = new ArrayList<>();
            securityListAdapter = new SecurityListAdapter(this, securities);
            securityListAdapter.setType(type);
            securityListAdapter.setClickListener(sClicklistener);
            dataRv.setAdapter(securityListAdapter);
        }
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            if (type == Constants.QUALITY || type == Constants.QUALITY_QUESTION|| type == Constants.QUALITY_SUPERVISE) {
                pageIndex = qualities.size() / Utils.ONCECOUNT + 1;
            }else {
                pageIndex = securities.size() / Utils.ONCECOUNT + 1;
            }
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getTestList(null);
            }
        }, 500);
    }

    private QualityListAdapter.ClickListener qClicklistener = new QualityListAdapter.ClickListener(){

        @Override
        public void onClick(int position) {
            Quality quality = qualities.get(position);
            Intent intent = new Intent();
            if (type == Constants.QUALITY||type == Constants.QUALITY_SUPERVISE) {
                intent.setClass(QualityListActivity.this, QualityTestActivity.class);
            }else if (type == Constants.QUALITY_QUESTION) {
                intent.setClass(QualityListActivity.this, QualityQuestionActivity.class);
            }
            intent.putExtra("quality", quality);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    };

    private SecurityListAdapter.ClickListener sClicklistener = new SecurityListAdapter.ClickListener(){

        @Override
        public void onClick(int position) {
            Security security = securities.get(position);
            Intent intent = new Intent();
            if (type == Constants.SECURITY) {
                intent.setClass(QualityListActivity.this, SecurityTestActivity.class);
            } else if (type == Constants.DAILY_SECURITY) {
                intent.setClass(QualityListActivity.this, DailySecurityTestActivity.class);
            } else if (type == Constants.SECURITY_QUESTION) {
                intent.setClass(QualityListActivity.this, SecurityQuestionActivity.class);
            }
            intent.putExtra("security", security);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    };

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
                Intent intent = new Intent();
                if (type == Constants.QUALITY||type == Constants.QUALITY_SUPERVISE) {
                    intent.setClass(this, QualityTestActivity.class);
//                    intent.putExtra("isLive", isLive);
                }else if(type == Constants.DAILY_SECURITY){
                    intent.setClass(this, DailySecurityTestActivity.class);
                }else if(type == Constants.SECURITY||type == Constants.SECURITY_SUPERVISE||type == Constants.CIVILIZED_CONSTRUCTION_SUPERVISE){
                    intent.setClass(this, SecurityTestActivity.class);
                }else if(type == Constants.SECURITY_QUESTION){
                    intent.setClass(this, SecurityQuestionActivity.class);
                }else if(type == Constants.QUALITY_QUESTION) {
                    intent.setClass(this, QualityQuestionActivity.class);
                }else if (type == Constants.LIVE) {
                    intent.setClass(this, QualityTestActivity.class);
//                    intent.putExtra("isLive", isLive);
                }
                intent.putExtra("type", type);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1 && requestCode == 1) {
            initData();
        }
    }

    private void getTestList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            if(type == Constants.QUALITY_QUESTION  || type == Constants.LIVE){
                jsonObject.put("type", Constants.QUALITY + "");
            }else if(type == Constants.SECURITY_QUESTION){
                jsonObject.put("type", Constants.DAILY_SECURITY + "");
            }else if(type == Constants.QUALITY_SUPERVISE ||
                    type == Constants.SECURITY_SUPERVISE ||
                    type == Constants.CIVILIZED_CONSTRUCTION_SUPERVISE) {
                jsonObject.put("type", type + "");
            }else{
                jsonObject.put("type", type + "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/inspection/queryByConstructionId/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    Message message = handler.obtainMessage();
                    if(type == Constants.QUALITY || type == Constants.QUALITY_QUESTION || type == Constants.QUALITY_SUPERVISE){
                        QualityListRes qualityListRes = gson.fromJson(json, QualityListRes.class);
                        if(qualityListRes.getStatus() == 1){
                            message.obj = qualityListRes.getValue();
                            message.what = Constants.UPDATE;
                            message.sendToTarget();
                        }else{
                            showToast(qualityListRes.getMsg());
                            if (pageIndex == 1)
                            {
                                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                            } else
                            {
                                refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                            }
                        }
                    }else{
                        SecurityListRes securityListRes = gson.fromJson(json, SecurityListRes.class);
                        if(securityListRes.getStatus() == 1){
                            message.obj = securityListRes.getValue();
                            message.what = Constants.UPDATE;
                            message.sendToTarget();
                        }else{
                            showToast(securityListRes.getMsg());
                            if (pageIndex == 1)
                            {
                                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                            } else
                            {
                                refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                            }
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void addQualityData(List<Quality> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            qualities = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            qualities.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        qualityListAdapter.setDataList(qualities);
    }

    private void addSecurityData(List<Security> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            securities = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            securities.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        securityListAdapter.setDataList(securities);
    }
}
